<template>
	<SelectUser :isRadio="isRadio" :isNeedSearch="isNeedSearch" :title="title" :userList="userList"
		@search="handleSearch" @complete="handleSelectedResult" />

</template>
<script lang="ts" setup>
	import {
		TUIFriendService,
		TUIUserService,
		TUIStore,
		StoreName,
		TUITranslateService,
	} from "@tencentcloud/chat-uikit-engine";
	import { onMounted, ref } from "../../../adapter-vue";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import SelectUser from "../../common/SelectUser/index.vue";
	const friendList = ref([]);
	const searchList = ref([]);//搜索用户
	const userList = ref([]);
	const source=ref('')
	const props = defineProps({
		isRadio: {
			type: Boolean,
			default: false
		},
		isNeedSearch: {
			type: Boolean,
			default: true
		},
		title: {
			type: String,
			default: ''
		},
	})
	const emits = defineEmits(['handleSelectedResult'])
	const getUserList = () => {
		TUIStore.watch(StoreName.FRIEND, {
			friendList: (data) => {
				friendList.value = data.map((item : any) => item.profile);
				userList.value = friendList.value
				console.log(userList.value, friendList.value, "我的好友列表")
			}
		})
	}
	onMounted(() => {
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data : any) => {
				if (data) {
				    source.value=data.source
				    getUserList()
				}
			}
		})
	})
	const handleSelectedResult = (memberList : Array<any>) => {
		emits('handleSelectedResult', memberList)
	};



	const handleSearch = async (val : string) => {
		if (!val) {
			//排除了我的好友的返回结果
			let arr = []
			if (searchList.value.length) {
				//筛选搜索结果和好友列表一样的用户  如果没有就是搜索结果是陌生人  加入展示列表里面
				arr = friendList.value.filter((item : any) => item.userID === searchList.value[0]?.userID);
				arr=arr.length===0?searchList.value:[]
			}
			userList.value = friendList.value.concat(arr);
			friendList.value=userList.value
			return
		}
		//获取所有用户
		try {
			const imResponse : any = await TUIUserService.getUserProfile({
				userIDList: [val+'_'+source.value]
			});
			if (!imResponse.data[0]) {
				searchList.value = []
				return userList.value = []
			}
			searchList.value = imResponse.data;
			userList.value = imResponse.data;
		} catch (error : any) {
			if (error.code === 3003) {
				uni.showToast({
					title: "聊天账号已在其他设备登录",
					icon: "none",
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/tabbar/index'
					})
				}, 1000)
				return null
			}
					
			Toast({
				message: TUITranslateService.t("TUISearch.查找联系人失败：") + error?.message,
				type: TOAST_TYPE.ERROR,
				duration: 1000,
			});
			userList.value = []
			return null
		}
	};
</script>